print("初始化程序……")

import os
import sys
import time

from random import random
from pathlib import Path
from PIL import Image
from multiprocessing import freeze_support

from utils.ConsoleIO import bool_str, format_ipt, int_str, ipt, prt
from utils.Constants import ADAPT, FILE_SAVE_SUFFIX
from utils.McStructure import SingleCommand, commands_to_structure
from utils.MediaOperation import image_list_2_string, resize_image

__version__ = "1.1.1"


def main():

    prt("完成！当前版本：", __version__)

    frame_list = None

    def output_format_should_be(x: str) -> int:
        if (rrs := int_str(x)) not in [1, 0]:
            raise ValueError("数值应为 0、1 之一。")
        return rrs

    def goprt(x_, x):
        prt(x_, x)
        return x

    pixel_height: int = format_ipt(
        "限制像素最大高（通常为150、每次增减30为佳）：", int_str, "请输入正确的整数。"
    )[1]

    if sys.argv.__len__() > 1:

        if os.path.isdir(sys.argv[1]):

            frame_list = [
                (
                    (
                        (
                            img_ := resize_image(
                                Image.open(goprt("已读取", cii)),
                                210,
                                pixel_height,
                                ADAPT,
                            )
                        ).tobytes(),
                        img_.mode,
                        *img_.size,
                    ),
                    cii,
                )
                for cii in Path(sys.argv[1]).iterdir()
                if cii.is_file()
                and (
                    cii.suffix.upper()
                    in (
                        ".JPG",
                        ".PNG",
                        ".BMP",
                    )
                )
            ]

            # output_file_name = ipt("输出文件名：")

    (
        output_path := Path(
            format_ipt("输出地址：", os.path.exists, "无法找到此目录。")[0]
        )
    ).mkdir(parents=True, exist_ok=True)
    is_coloured: bool = format_ipt(
        "启用彩色解析：", bool_str, "请输入正确的布尔格式。"
    )[1]

    is_coloured_band: bool = format_ipt(
        "使用彩色竖线条而非盲文点阵：", bool_str, "请输入正确的布尔格式。"
    )[1]

    if random() <= 0.3:
        flashing_your_eye: bool = format_ipt(
            "闪瞎人眼：", bool_str, "请输入正确的布尔格式。"
        )[1]
    else:
        flashing_your_eye = False

    output_format: int = format_ipt(
        "输出文件格式[0:mcfunction|1:mcstructure]：",
        output_format_should_be,
        "请输入正确的整数。",
    )[1]

    if frame_list is None:
        input_image_path: Path = Path(
            format_ipt("待转换图片地址：", os.path.exists, "地址不存在。")[0]
        )

        player_selector: str = ipt("玩家选择器：")

        if input_image_path.is_dir():
            frame_list = [
                (
                    (
                        (
                            img_ := resize_image(
                                Image.open(goprt("已读取", cii)),
                                210,
                                pixel_height,
                                ADAPT,
                            )
                        ).tobytes(),
                        img_.mode,
                        *img_.size,
                    ),
                    cii,
                )
                for cii in input_image_path.iterdir()
                if cii.is_file()
                and (
                    cii.suffix.upper()
                    in (
                        ".JPG",
                        ".PNG",
                        ".BMP",
                    )
                )
            ]
        elif input_image_path.is_file():
            frame_list = [
                (
                    (
                        (
                            img_ := resize_image(
                                Image.open(input_image_path), 210, pixel_height, ADAPT
                            )
                        ).tobytes(),
                        img_.mode,
                        *img_.size,
                    ),
                    input_image_path,
                )
            ]
        else:
            raise ValueError("你输入的地址……是啥？")

        # t = time.time()

        # if is_cached:
        #     pass
    else:
        player_selector: str = ipt("玩家选择器：")
        # t = time.time()

    if output_format == 0:
        for i, string in image_list_2_string(
            [img_info for img_info, _ in frame_list],
            is_coloured=is_coloured,
            is_coloured_band=is_coloured_band,
            rolling_length=35,
            flashing=flashing_your_eye,
        ):
            with (
                output_path
                / (
                    os.path.basename(frame_list[i][1].name)[::-1].split(".", 1)[1][::-1]
                    + ".mcfunction"
                )
            ).open("w+", encoding="utf-8") as f:
                f.write(
                    SingleCommand(
                        f"titleraw {player_selector} actionbar"
                        + '{"rawtext":[{"text":"'
                        + string.replace("\n", "\\n")
                        + '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n"}]}',
                        tick_delay=1,
                        annotation="由MVP生成",
                    ).cmd
                    + "\n"
                )

        ipt("完成输出，按下回车键退出程序")
    elif output_format == 1:

        struct, size, end_pos = commands_to_structure(
            [
                SingleCommand(
                    f"titleraw {player_selector} actionbar"
                    + '{"rawtext":[{"text":"'
                    + string.replace("\n", "\\n")
                    + '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n"}]}',
                    tick_delay=1,
                    annotation="由MVP生成",
                )
                for i, string in image_list_2_string(
                    [img_info for img_info, _ in frame_list],
                    is_coloured=is_coloured,
                    is_coloured_band=is_coloured_band,
                    rolling_length=35,
                    flashing=flashing_your_eye,
                )
            ],
            max_height=32,
        )

        with open(
            os.path.abspath(
                (k := input("输出文件名称："))
                + (
                    ""
                    if k.upper().endswith(
                        "MCSTRUCTURE",
                    )
                    else ".mcstructure"
                )
            ),
            "wb+",
        ) as f:
            struct.dump(f)

        ipt(
            "结构大小：{sz}\t终点位置：{ep}\n\n按下回车键退出".format(
                sz=size, ep=end_pos
            )
        )


if __name__ == "__main__":
    freeze_support()
    if os.getenv(FILE_SAVE_SUFFIX + "_MAIN") == "True":
        ipt(
            "[#F03432 on #4E4C9C]这一行代码不应该被运行，如果碰到了这行提示，请关闭程序"
        )
    else:
        os.environ[FILE_SAVE_SUFFIX + "_MAIN"] = "True"
        main()
